import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);






const store = new Vuex.Store({
	state: {
		isLogin: false,
		longitude: "",
		latitude: '',
		userInfo: {
			name: "未知用户",
			avatar: "/static/logo.png",
			num: "10"
		},
		needAuth: true,
		roleId: 0,
		tabBarList: []



	},
	mutations: {



		// 启动后初初化数据
		initUser(state) { //initUser自己随便起的名字
			let userInfo = {};
			if (uni.getStorageSync('userInfo')) {
				userInfo = uni.getStorageSync('userInfo');
				state.userInfo = userInfo
			}


			try {

				let isLogin = uni.getStorageSync('isLogin');
				let needAuth = uni.getStorageSync('needAuth');
				let roleId = uni.getStorageSync('roleId');
				//获取下面存储中setStorageSync里面的userInfo数据
				state.isLogin = isLogin
				state.needAuth = needAuth
				state.roleId = roleId ? roleId : '0'
				Vue.prototype.$setTabBarList(roleId);


			} catch (err) {

			}




		}

	},
	actions: {
		login(context) {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success(loginRes) {
						// 登录成功
						Vue.prototype.$u.api.wxLogin({
							appid: Vue.prototype.$appid,
							code: loginRes.code
						}).then(res => {
							uni.setStorageSync("token", res.data.token);

							if (res2.code === 200) {
								Vue.prototype.$setIsLogin(true);
								Vue.prototype.$setNeedAuth(false);
								Vue.prototype.$setUserInfo(res2.data.user);
							}
							// 返回值
							resolve(res2);
						}).catch(error => {
							reject(error);
						})

					},
					fail(err) {
						reject(err);
						// 登录授权失败  
						// err.code是错误码
					}
				});
			})
		},
		auth(context) {
			return new Promise((resolve, reject) => {
				wx.getUserProfile({
					desc: '用于完善会员资料',
					success: (res) => {
						let userInfo = {
							nickname: res.userInfo.nickName,
							avatar: res.userInfo.avatarUrl
						}
						Vue.prototype.$u.api.auth(userInfo).then(res2 => {

							if (res2.code === 200) {
								Vue.prototype.$log(res2);
								console.log("001")

								Vue.prototype.$setNeedAuth(false);
								Vue.prototype.$setIsLogin(true);
								resolve(true);
							} else {
								reject(false);
							}
						})
					},
					fail(err) {
						reject(err);
					}
				})
			})
		}



	},
	modules: [

	]



})

export default store